import {ExclamationCircleOutlined} from '@ant-design/icons';
import {Badge, Card, Col, Divider, Drawer, Form, InputNumber, message, Modal, Row, Select, Statistic, Tag} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import {
  allProcessOnline,
  assignedToMeProcessOnline,
  myAssignedProcessOnline,
  queryProcessOnlineMi,
  queryProductionProcessStatusByProductionNo,
  queryProductionStatusByProductionNo,
  receiveProcessOnline,
  rejectProcessOnline, transferProcessAvailableProcess,
  transferProcessOnline,
  transferProcessPacking
} from '@/services/process';
import {queryWarehouse} from "@/services/warehouse";


const TableList = () => {
  const dataList = [
    {
      key: 1,
      orderId: 'ORD000001',
      productCode: 'PRD000001',
      processCode: 'PRO000001',
      num: 10000,
      process: [
        {
          cKey: 1,
          receiveStatus: '未接收',
          lastProcessFlow: '生产计划',
          designator: '张三',
          designateNum: 1000,
          currentProcessFlow: '开料',
          beDesignator: '王五',
          toBeProcessedNum: 9000,
          designateTime: new Date(),
        },
        {
          cKey: 2,
          receiveStatus: '未接收',
          lastProcessFlow: '生产计划',
          designator: '张三',
          designateNum: 1000,
          currentProcessFlow: '开料',
          beDesignator: '王五',
          toBeProcessedNum: 9000,
          designateTime: new Date(),
        },
      ]
    },
    {
      key: 2,
      orderId: 'ORD000002',
      productCode: 'PRD000001',
      processCode: 'PRO000001',
      num: 10000,
      process: [
        {
          cKey: 1,
          receiveStatus: '未接收',
          lastProcessFlow: '生产计划',
          designator: '张三',
          designateNum: 1000,
          currentProcessFlow: '开料',
          beDesignator: '王五',
          toBeProcessedNum: 9000,
          designateTime: new Date(),
        }
      ]
    },
    {
      key: 3,
      orderId: 'ORD000003',
      productCode: 'PRD000001',
      processCode: 'PRO000001',
      num: 10000,
      process: [
        {
          cKey: 1,
          receiveStatus: '已接收',
          lastProcessFlow: '生产计划',
          designator: '张三',
          designateNum: 1000,
          currentProcessFlow: '开料',
          beDesignator: '王五',
          toBeProcessedNum: 9000,
          designateTime: new Date(),
        },
        {
          cKey: 2,
          receiveStatus: '已接收',
          lastProcessFlow: '生产计划',
          designator: '张三',
          designateNum: 1000,
          currentProcessFlow: '开料',
          beDesignator: '王五',
          toBeProcessedNum: 9000,
          designateTime: new Date(),
        },
        {
          cKey: 3,
          receiveStatus: '未接收',
          lastProcessFlow: '生产计划',
          designator: '张三',
          designateNum: 1000,
          currentProcessFlow: '开料',
          beDesignator: '王五',
          toBeProcessedNum: 9000,
          designateTime: new Date(),
        },
      ]
    },
  ]
  const [transferModalVisible, handleTransferModalVisible] = useState(false);
  const [packageModalVisible, handlePackageModalVisible] = useState(false);
  const [warehouseData, setWarehouseData] = useState([]);
  const [activekey, setActiveKey] = useState('tab1');
  const [detailVisible, setDetailVisible] = useState(false);
  const [formTitle, setFormTitle] = useState('新增入库');
  const [selectedRow, setSelectedRow] = useState({});
  const [selectedProcess, setSelectedProcess] = useState({});
  const [processStatiscData, setProcessStatiscData] = useState([]);
  const [availableProcess, setAvailableProcess] = useState([]);
  const [transferProcessDisabled, setTransferProcessDisabled] = useState(true);
  const actionRef = useRef();
  const productionStatisticsRef = useRef();
  const miRef = useRef();
  const historyRef = useRef();
  const [formRef] = Form.useForm();
  const [transferForm] = Form.useForm();
  const [packageForm] = Form.useForm();
  const [row, setRow] = useState();
  const {Option} = Select;
  useEffect(() => {
    queryWarehouse({
      pageNum: 1,
      pageSize: 999999
    }).then(res => {
      if (res && res.status === '0') {
        setWarehouseData(res.result.records)
      }
    })
  }, [])

  const showTransferModal = (record) => {
    handleTransferModalVisible(true)
    transferForm.setFieldsValue({
      defectNum: null,
      scrapNum: null,
      transferNum: null,
      transferProcessId: null
    })
    setTransferProcessDisabled(true)
    transferProcessAvailableProcess(record).then(res => {
      if (res.status === '0') {
        setAvailableProcess(res.data)
      }
    })
    setSelectedRow(record)
  }

  const showPackageModal = (record) => {
    handlePackageModalVisible(true)
    transferForm.setFieldsValue({
      defectNum: null,
      scrapNum: null,
      transferNum: null,
      marginNum: null,
      warehouseId: null
    })
    setSelectedRow(record)
  }

  const handleReceiveProcessOnline = (record) => {
    receiveProcessOnline(record).then(res => {
      if (res && res.status === '0') {
        message.success('接收成功')
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error(res.message)
      }
    })
  }

  const showReceiveConfirm = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `请确认是否接收该工艺段？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const success = await handleReceiveProcessOnline(record)
      }
    });
  };

  const handleRejectProcessOnline = (record) => {
    rejectProcessOnline(record).then(res => {
      if (res && res.status === '0') {
        message.success('驳回成功')
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error(res.message)
      }
    })
  }

  const showRejectConfirm = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `请确认是否驳回该工艺段？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const success = await handleRejectProcessOnline(record)
      }
    });
  };

  const handleTransferSubmit = () => {
    transferForm.validateFields().then(value => {
      if (value.defectNum > 0) {
        if (!value.transferProcessId) {
          message.error('请选择返工至工艺段')
          return;
        }
      }
      const param = {
        id: selectedRow.pkId,
        ...value
      };
      transferProcessOnline(param).then(res => {
        if (res && res.status === '0') {
          message.success('流转成功')
          handleTransferModalVisible(false)
          setSelectedRow({})
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message)
        }
      })
    })
    // const fromData = transferForm.getFieldsValue();

  }

  const handlePackageInSubmit = () => {
    packageForm.validateFields().then(value => {
      const param = {
        id: selectedRow.pkId,
        ...value
      };
      transferProcessPacking(param).then(res => {
        if (res && res.status === '0') {
          message.success('入库成功')
          handlePackageModalVisible(false)
          setSelectedRow({})
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message)
        }
      })
    })
  }

  const queryProductionStastics = (record) => {
    queryProductionStatusByProductionNo(record).then(res => {
      if (res && res.status === '0') {
        setProcessStatiscData(res.data)
      }
    })
  }

  const onDefectNumChange = (v) => {
    if (v === 0) {
      transferForm.setFieldsValue({
        transferProcessId: null
      })
      setTransferProcessDisabled(true)
    }else {
      setTransferProcessDisabled(false)
    }
  }

  const renderBadge = (count, active = false) => {
    return (
      <Badge
        // count={count}
        style={{
          marginTop: -2,
          marginLeft: 4,
          color: active ? '#1890FF' : '#999',
          backgroundColor: active ? '#E6F7FF' : '#eee',
        }}
      />
    );
  };
  const columns = [
    {
      title: '订单编号',
      width: 100,
      dataIndex: 'orderCode',
    },
    {
      title: '产品编号',
      width: 100,
      dataIndex: 'productCode'
    },
    {
      title: '生产编号',
      width: 100,
      dataIndex: 'productionNo',
    },
    {
      title: '订货量',
      width: 600,
      dataIndex: 'orderNum',
      hideInSearch: true
    },
    {
      title: '',
      dataIndex: 'operation',
      key: 'operation',
      width: 50,
      valueType: 'option',
      hideInTable: activekey === 'tab3' ? false : true,
      render: (_, record) => {
        return [<a onClick={() => {
          setDetailVisible(true)
          queryProductionStastics(record)
          setSelectedProcess(record)
          // if (productionStatisticsRef.current) {
          //   productionStatisticsRef.current.reload()
          // }
        }
        }>生产情况</a>]
      }
    },
    {
      title: '接收状态',
      dataIndex: 'receiveStatus',
      key: 'name',
      hideInTable: true, hideInSearch: true,
      render: (text, record) => {
        return <Tag color={text === 1 ? 'red' : 'green'}>{text === 1 ? '未接收' : '已接收'}</Tag>
      }
    },
    {title: '上一工艺段', dataIndex: 'lastProcessName', key: 'lastProcessName', hideInTable: true, hideInSearch: true},
    {title: '指派人', dataIndex: 'assignedFromName', key: 'assignedFromName', hideInTable: true, hideInSearch: true},
    {title: '指派数量', dataIndex: 'assignedNum', key: 'assignedNum', hideInTable: true, hideInSearch: true},
    {title: '当前工艺段', dataIndex: 'nowProcessName', key: 'nowProcessName', hideInTable: true, hideInSearch: true},
    {title: '被指派人', dataIndex: 'assignedToNames', key: 'assignedToNames', hideInTable: true, hideInSearch: true},
    {title: '待工艺数量', dataIndex: 'toBeProducedNum', key: 'toBeProducedNum', hideInTable: true, hideInSearch: true},
    {title: '指派时间', dataIndex: 'assignedTime', key: 'assignedTime', hideInTable: true, hideInSearch: true},
  ];
  const detailColumns = (parentRecord) => {
    return [
      {
        title: '序号', dataIndex: 'cKey', key: 'date',
        render: (text, record, index) => {
          return index + 1
        }
      },
      {
        title: '接收状态', dataIndex: 'receiveStatus', key: 'name',
        render: (text, record) => {
          return <Tag color={text === 1 ? 'red' : 'green'}>{text === 1 ? '未接收' : '已接收'}</Tag>
        }
      },
      {title: '上一工艺段', dataIndex: 'lastProcessName', key: 'lastProcessName'},
      {title: '指派人', dataIndex: 'assignedFromName', key: 'assignedFromName'},
      {title: '指派数量', dataIndex: 'assignedNum', key: 'assignedNum'},
      {title: '当前工艺段', dataIndex: 'nowProcessName', key: 'nowProcessName'},
      {title: '被指派人', dataIndex: 'assignedToNames', key: 'assignedToNames'},
      {title: '待工艺数量', dataIndex: 'toBeProducedNum', key: 'toBeProducedNum'},
      {title: '指派时间', dataIndex: 'assignedTime', valueType: 'dateTime', key: 'assignedTime'},
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        valueType: 'option',
        render: (_, record) => {
          // let row1 = {...parentRecord, ...record};
          const tab1Buttons = [
            <a onClick={() => {
              setRow(record)
              if (miRef.current) {
                miRef.current.reload();
              }
            }}>详情</a>,
            <Divider style={{display: record.receiveStatus === 1 ? '' : 'none'}} type={"vertical"}/>,
            <a style={{display: record.receiveStatus === 1 ? '' : 'none'}}
               onClick={() => showReceiveConfirm(record)}>接收</a>,
            <Divider style={{display: record.receiveStatus === 1 ? '' : 'none'}} type={"vertical"}/>,
            <a style={{display: record.receiveStatus === 1 && record.nowProcessId !== 6 ? '' : 'none'}}
               onClick={() => showRejectConfirm(record)}>驳回</a>,
            <Divider style={{display: record.receiveStatus === 2 ? '' : 'none'}} type={"vertical"}/>,
            <a style={{display: record.receiveStatus === 2 && record.nowProcessId !== 58 ? '' : 'none'}}
               onClick={() => showTransferModal(record)}>流转下一工艺段</a>,
            <Divider style={{display: record.receiveStatus === 2 && record.nowProcessId === 58 ? '' : 'none'}}
                     type={"vertical"}/>,
            <a style={{display: record.receiveStatus === 2 && record.nowProcessId === 58 ? '' : 'none'}}
               onClick={() => showPackageModal(record)}>包装入库</a>,
          ]
          const tab23Buttons = [<a onClick={() => setRow(record)}>详情</a>]
          return activekey === 'tab1' ? tab1Buttons : tab23Buttons
        },
      },
    ]
  }
  const miColumns = [
    {
      title: '产品编码',
      width: 100,
      dataIndex: 'productCode',
    },
    {
      title: '工艺流程名称',
      width: 100,
      dataIndex: 'processName'
    },
    // {
    //   title: 'mi参数id',
    //   width: 100,
    //   dataIndex: 'miId',
    // },
    {
      title: 'mi参数名称',
      width: 100,
      dataIndex: 'miName',
    },
    {
      title: 'mi参数值',
      width: 100,
      dataIndex: 'miValue'
    },
    {
      title: '描述',
      width: 100,
      dataIndex: 'remark',
    },
  ]
  const expandedRowRender = (record) => {
    return (<ProTable columns={detailColumns(record)} headerTitle={false} search={false} options={false} rowKey={'pkId'}
                      dataSource={record.techOnlineList} pagination={false}/>);
  };

  return (
    <PageContainer
    >
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={async (params, sorter, filter) => {
          const param = {...params, pageNum: params.current};
          const res = activekey === 'tab1' ? await assignedToMeProcessOnline(param) : (activekey === 'tab2' ? await myAssignedProcessOnline(param) : await allProcessOnline(param))
          // const oldData = res.result.records;
          // const newData = [];
          // const newDataIds = [];
          // for (const item of oldData) {
          //   if (newDataIds.indexOf(item.orderId) < 0) {
          //     newDataIds.push(item.orderId)
          //     item.process = [{...item}] // 放在children里
          //     newData.push({...item})
          //   } else {
          //     newData.map(newItem => {
          //       if (newItem.orderId === item.orderId) {
          //         newItem.process.push({...item}) // 放在children里
          //       }
          //       return newItem
          //     })
          //   }
          // }
          const newData = res.result.records.map(order=>{
            order.techOnlineList.map(online=>{
              online.orderCode = order.orderCode;
              online.orderNum = order.orderNum;
              online.productionNo = order.productionNo;
              online.productionNum = order.productionNum;
              return online;
            })

            return order;
          })
          return {
            data: newData,
            success: true,
            total: res.result.total
          }
        }}
        rowKey="orderId"
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activekey,
            items: [
              {
                key: 'tab1',
                label: <span>指派给我的{renderBadge(99, activekey === 'tab1')}</span>,
              },
              {
                key: 'tab2',
                label: <span>我指派的{renderBadge(30, activekey === 'tab2')}</span>,
              },
              {
                key: 'tab3',
                label: <span>所有在途{renderBadge(30, activekey === 'tab3')}</span>,
              },
            ],
            onChange: (key) => {
              setActiveKey(key);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            },
          },
        }}
        pagination={{
          showQuickJumper: true,
        }}
        expandable={{expandedRowRender: expandedRowRender, defaultExpandAllRows: true, indentSize: 500}}
        dateFormatter="string"/>
      <Modal
        destroyOnClose
        title={'流转下一工艺段'}
        width={800}
        visible={transferModalVisible}
        onCancel={() => handleTransferModalVisible(false)}
        wrapClassName={'normalModal'}
        onOk={(e) => handleTransferSubmit()}
      >
        <Form form={transferForm} name="transferForm">
          <Form.Item name="transferNum" label="流转数量" rules={[
            {
              required: true,
            },
            {
              pattern: /^[1-9]\d*$/,
              message: '只能输入整数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={1}/>
          </Form.Item>
          <Form.Item name="defectNum" label="不良品数量" rules={[
            {
              pattern: /^[0-9]\d*$/,
              message: '只能输入整数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={0} onChange={(v) => onDefectNumChange(v)}/>
          </Form.Item>
          <Form.Item name="transferProcessId" label="返工至工艺段">
            <Select disabled={transferProcessDisabled}>
              {
                availableProcess.map(item => {
                  return <Option value={item.processId} key={item.processId}>{item.processName}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item name="scrapNum" label="报废数量" rules={[
            {
              pattern: /^[0-9]\d*$/,
              message: '只能输入整数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={0}/>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        destroyOnClose
        title={'包装入库'}
        width={800}
        visible={packageModalVisible}
        onCancel={() => handlePackageModalVisible(false)}
        wrapClassName={'normalModal'}
        onOk={() => handlePackageInSubmit()}
      >
        <Form form={packageForm} name="transferForm">
          <Form.Item name="warehouseId" label="仓库" rules={[
            {
              required: true,
            }
          ]}>
            <Select>
              {
                warehouseData.map(item => {
                  return <Option value={item.warehouseId} key={item.warehouseId}>{item.warehouseName}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item name="transferNum" label="入库数量" rules={[
            {
              required: true,
            },
            {
              pattern: /^[1-9]\d*$/,
              message: '只能输入整数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={1}/>
          </Form.Item>
          <Form.Item name="marginNum" label="其中包含备品数量" rules={[
            {
              required: true,
            },
            {
              pattern: /^[0-9]\d*$/,
              message: '只能输入整数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={1}/>
          </Form.Item>
          <Form.Item name="defectNum" label="不良品数量" tooltip={'不良品产品将返工到上一工艺段'} rules={[
            {
              pattern: /^[0-9]\d*$/,
              message: '只能输入整数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={0}/>
          </Form.Item>
          <Form.Item name="scrapNum" label="报废数量" rules={[
            {
              pattern: /^[0-9]\d*$/,
              message: '只能输入整数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={0}/>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        destroyOnClose
        title={'生产情况'}
        width={800}
        visible={detailVisible}
        footer={null}
        onCancel={() => setDetailVisible(false)}
        wrapClassName={'processDetailModal'}
      >
        <>
          <h3>投产量</h3>
          <div>{selectedProcess.productionNum}</div>
          <h3>待生产情况</h3>
          <Row gutter={16}>
            {
              processStatiscData.map(item => {
                return <Col span={6} key={item.processName} style={{marginBottom: '10px'}}>
                  <Card>
                    <Statistic
                      title={item.processName}
                      value={item.toBeProducedNum}
                    />
                  </Card>
                </Col>
              })
            }
          </Row>
          <h3>工艺段统计</h3>
          <ProTable
            actionRef={productionStatisticsRef}
            columns={[
              {
                title: '工艺段',
                dataIndex: 'processName',
                key: 'processName'
              },
              {
                title: '已生产数量',
                dataIndex: 'productNum',
                key: 'productNum'
              },
              {
                title: '不良数量',
                dataIndex: 'defectNum',
                key: 'defectNum'
              },
              {
                title: '不良率',
                dataIndex: 'defectRatio',
                key: 'defectRatio',
                render: (text) => {
                  return (text * 100).toFixed(2) + '%'
                }
              },
              {
                title: '报废数量',
                dataIndex: 'scrapNum',
                key: 'scrapNum'
              },
              {
                title: '报废率',
                dataIndex: 'scrapRatio',
                key: 'scrapRatio',
                render: (text) => {
                  return (text * 100).toFixed(2) + '%'
                }
              },
            ]}
            headerTitle={false}
            search={false}
            options={false}
            request={async (params, sorter, filter) => {
              const res = await queryProductionProcessStatusByProductionNo(selectedProcess)
              return {
                data: res.data,
                success: true,
                total: res.data.size
              }
            }}
            pagination={false}/>
        </>
      </Modal>
      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.orderId && (
          <ProDescriptions
            column={2}
            title={'基础信息'}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.orderId,
            }}
            columns={columns}
          />
        )}
        <ProTable
          rowKey="miId"
          actionRef={miRef}
          headerTitle="当前工艺段MI参数"
          toolbar={false}
          options={false}
          request={async () => {
            const res = await queryProcessOnlineMi({
              processId: row.nowProcessId,
              productCode: row.productCode
            })
            return {
              data: res.data,
              success: true,
              total: res.data.length
            }
          }}
          search={false}
          pagination={false}
          columns={miColumns}
        />
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
